<?php

namespace app\service;

use app\common\BaseService;
use app\model\HouseOut as HouseOutModel;
use think\facade\Db;

class HouseOutService extends BaseService
{
  public static function getInstance(): HouseOutService
  {
    return parent::getInstance();
  }

  public static function getModel(): HouseOutModel
  {
    return HouseOutModel::getInstance();
  }

  /*
   * 连商品表goods查询house_out信息
   */
  public function getHouseOutJoinGoods($conditions = [], $order = ['h.id' => 'DESC']) {
//    $lock ? true : $conditions[] = ['h.status', 1,'='];
    $query = Db::name('house_out')
      ->alias('h')
      ->field('h.*, g.category_id, g.name, g.unit, g.specs, g.sale_name, c.category_name, hn.count as house_count, u.basename')
      ->join('goods g', 'g.id = h.goods_id', 'LEFT')
      ->join('category c', 'g.category_id = c.id', 'LEFT')
      ->join('user u', 'u.base = h.base', 'LEFT')
      ->join('house hn', 'hn.goods_id = h.goods_id', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    return $query->select()->toArray();
  }

  /*
   * 删除house_out信息
   */
  public static function deleteHouseOut($id, $type) {
    // 获取入库详情
    $houseOut = self::getModel()
      ->where('id', '=', $id)
      ->find()
      ->toArray();
    // 获取house表实时数据
    $house = HouseService::getInstance()->getHouseJoinGoods([['goods_id', $houseOut['goods_id'], '=']]);
    $house = isset($house[0]) ? $house[0] : [];
    // 更新house表
    $updateHouse = [
      'count' => $house['count'] + $houseOut['count'],
      'total_amount' => round($house['total_amount'] + ($houseOut['price'] * $houseOut['count']), 2),
      'price' => round(($house['total_amount'] + $houseOut['price'] * $houseOut['count'])/($house['count'] + $houseOut['count']), 2),
      'last_update_time' => date('Y-m-d')
    ];
    // 更新store_house表
    $updateStore = [];
    if ($type == 2) {
      // 查询门店已有库存
      $store = StoreService::getInstance()->getDataByCondition([
        ['name', $house['sale_name'], '='],
        ['base', $houseOut['base'], '=']
      ]);
      if (!isset($store[0])) {
        return ['status' => false, 'msg' => '数据有误，删除失败'];
      }
      $store = $store[0];
      if ($store['count'] - $houseOut['count'] < 0) {
        return ['status' => false, 'msg' => '门店库存不足'];
      }
      // 获取门店当前数据
      $totalAmount = round($store['total_amount'] - ($houseOut['count'] * $houseOut['sell_price']), 2);
      $updateStore = [
        'goods_id' => $houseOut['goods_id'],
        'category_id' => $house['category_id'],
        'count' => $store['count'] - $houseOut['count'],
        'total_amount' => $totalAmount,
        'price' => $store['count'] - $houseOut['count'] ? round($totalAmount/($store['count'] - $houseOut['count']), 2) : 0
      ];
    }
    self::getModel()->startTrans();
    try {
      // 更新house表
      if ($updateHouse) {
        $res1 = HouseService::getModel()
          ->where('id', '=', $house['id'])
          ->save($updateHouse);
        if ($res1 === false) {
          throw new \Exception('更新house失败');
        }
      }
      // 更新house_out表
      $res2 = self::getModel()
        ->where('id', '=', $id)
        ->save(['status' => 0, 'last_update_time' => date('Y-m-d')]);
      if ($res2 === false) {
        throw new \Exception('更新house_out失败');
      }
      // 售出要修改门店仓库数据
      if ($type == 2) {
        // 更新store_house
        if ($updateStore) {
          $res3 = StoreService::getModel()
            ->where('id', '=', $store['id'])
            ->save($updateStore);
          if ($res3 === false) {
            throw new \Exception('更新store_house失败');
          }
        }
        // 更新inner_purchase
        $res4 = InnerPurchaseService::getModel()
          ->where('house_out_id', '=', $id)
          ->save(['status' => 0, 'last_update_time' => date('Y-m-d')]);
        if ($res4 === false) {
          throw new \Exception('更新inner_purchase失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 通过condition获取HouseOut
   */
  public function getHouseOutByCondition($conditions, $order = ['id' => 'desc']) {
    $query = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order($order);
    $result = $query->select()->toArray();
    return $result;
  }


}